package krow.dev.contest.controller;

import java.util.ArrayList;
import java.util.List;

import krow.dev.contest.model.FavoriteItem;
import krow.dev.contest.model.MyProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.AsyncTask;
import android.util.Log;

public class FavoriteListFactory extends AsyncTask<Void, Void, Boolean> {

	private DbOpenHelper mDbOpenHelper;
	
	private Cursor mCursor;
	
	private Context mContext;
	
	private List<FavoriteItem> mFavoriteItemList;
	
	private OnCompletionListener mCompletionListener;

	
	private boolean mIsCancelled;
	
	
	public FavoriteListFactory(Context context) {

		mContext = context;
		
		mFavoriteItemList = new ArrayList<FavoriteItem>();
	}

	public void setCompletionListener(OnCompletionListener completionListener) {

		mCompletionListener = completionListener;
	}

	public void cancel() {

		mIsCancelled = true;
	}

	@Override
	protected void onPreExecute() {
		
	}

	@Override
	protected Boolean doInBackground(Void... params) {

		return request();
	}

	@Override
	protected void onPostExecute(Boolean result) {
		

		if (result && !mIsCancelled) {
			if (mCompletionListener != null) {
				mCompletionListener.onCompletion(mFavoriteItemList);
			}
		}
	}

	private boolean request() {
		System.out.println("팩토리 진입 완료");
		boolean isSucceed = true;
		
		mDbOpenHelper = new DbOpenHelper(mContext);
        mDbOpenHelper.open();
		
		mCursor = null;
        mCursor = mDbOpenHelper.getAllColumns();
        
        Log.e("페보릿리스트팩토리", "COUNT = " + mCursor.getCount());
		
		try {
			
			while (mCursor.moveToNext()) {
	             
				FavoriteItem favoriteItem = new FavoriteItem();
				favoriteItem.setTitle(mCursor.getString(mCursor.getColumnIndex("title")));
				favoriteItem.setDepartment(mCursor.getString(mCursor.getColumnIndex("department")));
				favoriteItem.setDescription(mCursor.getString(mCursor.getColumnIndex("descript"))); 
				favoriteItem.setLink(mCursor.getString(mCursor.getColumnIndex("url")));
				favoriteItem.setCreator(mCursor.getString(mCursor.getColumnIndex("creator")));

				mFavoriteItemList.add(favoriteItem);
	        }
	         
	        mCursor.close();
			
			
			 	
		} catch (Exception e) {
			System.out.println(e.getMessage());
			isSucceed = false;
		}
		
		return isSucceed;
	}
	
	
	
	public interface OnCompletionListener {

		public abstract void onCompletion(List<FavoriteItem> favoriteItemList);
	}
}
